package com.asynctm.android.tm.activity;

import java.util.LinkedList;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.asynctm.android.R;
import com.asynctm.android.common.application.AsyncTMApplication;
import com.asynctm.android.common.application.BaseActivity;
import com.asynctm.android.common.exception.DaoException;
import com.asynctm.android.common.util.ApplicationUtil;
import com.asynctm.android.tm.dao.TaskDao;
import com.asynctm.android.tm.dao.TaskDaoImpl;
import com.asynctm.android.tm.dto.ActivityDto;

/**
 * Pantalla de seleccion de actividades
 * 
 * @author rockdrigo
 */
public class TaskManagerActivity extends BaseActivity implements
		OnClickListener {

	private final String LOG_TAG = TaskManagerActivity.class.getSimpleName()
			.toString();
	private ProgressDialog progressDialog;
	private TaskManagerActivityViewHolder viewHolder;
	private WriteListAsyncTask writeAsyncTask;
	private CheckListAsyncTask readAsyncTask;
	private boolean selector;
	private AlertDialog alertDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.task_manager);
		setName(LOG_TAG);

		viewHolder = new TaskManagerActivityViewHolder(this);
		viewHolder.setOnClickListener(this);
		
		viewHolder.getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				((AsyncTMApplication) getApplicationContext()).removeActivity(arg2);
				viewHolder.populateMovements(getApplicationContext());
			}
		});

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (selector) {
				viewHolder.getViewFlipper().showPrevious();
				selector = false;
				writeAsyncTask = new WriteListAsyncTask();
				writeAsyncTask.execute(new Void[] {});
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		if (selector) {
			viewHolder.getViewFlipper().showPrevious();
			selector = false;
			writeAsyncTask = new WriteListAsyncTask();
			writeAsyncTask.execute(new Void[] {});
		}
	}

	@Override
	public void onClick(View v) {

		if (v == viewHolder.getBtnAnniversary()) {
			readAsyncTask = new CheckListAsyncTask("anniversary.txt");
			readAsyncTask.execute(new Void[] {});
		} else if (v == viewHolder.getBtnBirthday()) {
			readAsyncTask = new CheckListAsyncTask("birthday.txt");
			readAsyncTask.execute(new Void[] {});
		} else if (v == viewHolder.getBtnHomework()) {
			readAsyncTask = new CheckListAsyncTask("homework.txt");
			readAsyncTask.execute(new Void[] {});
		} else if (v == viewHolder.getBtnJourney()) {
			readAsyncTask = new CheckListAsyncTask("journey.txt");
			readAsyncTask.execute(new Void[] {});
		} else if (v == viewHolder.getBtnNotes()) {
			readAsyncTask = new CheckListAsyncTask("notes.txt");
			readAsyncTask.execute(new Void[] {});
		} else if (v == viewHolder.getBtnReminder()) {
			readAsyncTask = new CheckListAsyncTask("reminder.txt");
			readAsyncTask.execute(new Void[] {});
		} else if (v == viewHolder.getBtnAdd()) {
			displayDialog();
		} 

	}

	/**
	 * Realiza la peticion de lectura de datos
	 * 
	 * @author rockdrigo
	 * 
	 */
	private class CheckListAsyncTask extends AsyncTask<Void, Void, Object> {

		private DaoException generatedException;
		private TaskDao taskDao;
		private LinkedList<ActivityDto> activityDto;
		private String path;

		public CheckListAsyncTask(String path) {
			this.path = path;
		}
		
		public String getPath() {
			return path;
		}
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();

			progressDialog = ProgressDialog.show(TaskManagerActivity.this, "",
					getString(R.string.msg_default_progress));

			taskDao = new TaskDaoImpl();
		}

		@Override
		protected Object doInBackground(Void... arg0) {
			try {
				activityDto = (LinkedList<ActivityDto>) taskDao.getTask(path);
			} catch (DaoException e) {
				generatedException = e;
				Log.e(LOG_TAG, "Error al parcear: ", e);
			}
			return null;
		}

		@Override
		protected void onPostExecute(Object result) {
			super.onPostExecute(result);
			if (generatedException != null) {
				if (!ApplicationUtil.comprobarSDCard(getApplicationContext())) {
					ApplicationUtil
							.showServiceUnavailableDialog(TaskManagerActivity.this);
				}
			} else {
				if (!activityDto.isEmpty()) {
					Log.d(LOG_TAG, "HomeAction ejecutado ... ");
					((AsyncTMApplication) getApplicationContext())
							.setActivities(activityDto);
					viewHolder.populateMovements(getApplicationContext());
					selector = true;
					viewHolder.getViewFlipper().showNext();

				} else {
					Log.d(LOG_TAG, "ListaVacia erroneo ...");
					((AsyncTMApplication) getApplicationContext())
					.setActivities(activityDto);
					Toast.makeText(TaskManagerActivity.this,
							"¡No se encontraron datos, agrega una nueva tarea!", Toast.LENGTH_SHORT)
							.show();
					selector = true;
					viewHolder.getViewFlipper().showNext();
					displayDialog();
				}

			}

			progressDialog.dismiss();

		}

	}

	/**
	 * Realiza la peticion de escritura de datos
	 * 
	 * @author rockdrigo
	 * 
	 */
	private class WriteListAsyncTask extends AsyncTask<Void, Void, Object> {

		private DaoException generatedException;
		private TaskDao taskDao;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();

			progressDialog = ProgressDialog.show(TaskManagerActivity.this, "",
					getString(R.string.msg_default_progress));

			taskDao = new TaskDaoImpl();
		}

		@Override
		protected Object doInBackground(Void... arg0) {
			try {
				taskDao.writeTask(((AsyncTMApplication) getApplicationContext())
						.getActivities(), readAsyncTask.getPath());
			} catch (DaoException e) {
				generatedException = e;
				Log.e(LOG_TAG, "Error al parcear: ", e);
			}
			return null;
		}

		@Override
		protected void onPostExecute(Object result) {
			super.onPostExecute(result);
			if (generatedException != null) {
				if (!ApplicationUtil.comprobarSDCard(getApplicationContext())) {
					ApplicationUtil
							.showServiceUnavailableDialog(TaskManagerActivity.this);
				}
			} else {
				if (ApplicationUtil.comprobarSDCard(getApplicationContext())) {
					Log.d(LOG_TAG, "Guardado ejecutado ... ");
				} else {
					Log.d(LOG_TAG, "ListaVacia erroneo ...");
					Toast.makeText(TaskManagerActivity.this,
							"Error al guardar datos.", Toast.LENGTH_SHORT)
							.show();
				}

			}

			progressDialog.dismiss();

		}

	}

	/**
	 * Controlador del AlertDialog personalizado
	 */
	private void displayDialog() {

		AlertDialog.Builder dialog = new AlertDialog.Builder(
				TaskManagerActivity.this);

		LayoutInflater inflater = (LayoutInflater) TaskManagerActivity.this
				.getSystemService(LAYOUT_INFLATER_SERVICE);

		View layout = inflater.inflate(R.layout.task_input, null);

		final EditText etName = (EditText) layout
				.findViewById(R.id.etInputName);
		final EditText etDescription = (EditText) layout
				.findViewById(R.id.etInputDescription);
		final EditText etDate = (EditText) layout
				.findViewById(R.id.etInputFecha);
		Button send = (Button) layout.findViewById(R.id.btnSend);

		dialog.setView(layout);

		alertDialog = dialog.create();

		send.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				ActivityDto act = new ActivityDto();
				act.setActivityName(etName.getText().toString());
				act.setActivityDescription(etDescription.getText().toString());
				act.setActivityDate(etDate.getText().toString());
				((AsyncTMApplication) getApplicationContext()).addActivities(act);
				viewHolder.populateMovements(getApplicationContext());
				alertDialog.dismiss();
			}
		});

		alertDialog.show();

	}
}
